package com.iflytek.jzcpx.procuracy.common.result;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.iflytek.jzcpx.procuracy.common.enums.CommonResultEnum;
import com.iflytek.jzcpx.procuracy.common.enums.ResultType;
import lombok.Data;

/**
 * web 层响应
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-09 19:10
 */
@Data
@JsonIgnoreProperties({"fileId"})
public class WebResult<T> {
    /** 请求是否成功 */
    private Boolean success;

    /** 状态码 */
    private int code;

    /** 状态描述 */
    private String message;

    /** 数据 */
    private T data;
    
    /**
     * fileId 指标收集用
     */
    private Long fileId;

    public WebResult() {
    }

    public WebResult(ResultType resultType) {
        this.code = resultType.getCode();
        this.message = resultType.getDesc();
    }

    public WebResult(ResultType resultType, T data) {
        this(resultType);
        this.data = data;
    }

    public WebResult(ResultType resultType, String customMsg) {
        this(resultType);
        this.message = customMsg;
    }

    public boolean isSuccess() {
        return this.success == null ? this.code == ResultType.SUCCESS : this.success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    /** 构造默认的成功响应 */
    public static WebResult<?> success() {
        return new WebResult(CommonResultEnum.SUCCESS);
    }

    /** 构造的成功响应 */
    public static <T> WebResult<T> success(T data) {
        return new WebResult<>(CommonResultEnum.SUCCESS, data);
    }

    /** 构造无结果的成功响应 */
    public static <T> WebResult<T> success(Class<T> dataClass) {
        return new WebResult<>(CommonResultEnum.SUCCESS);
    }

    /** 构造自定义错误信息的默认失败响应 */
    public static WebResult<?> failed(String customMsg) {
        return new WebResult(CommonResultEnum.FAILED, customMsg);
    }

    /** 构造自定义错误码和错误信息的失败响应 */
    public static WebResult<?> failed(ResultType resultEnum, String customMsg) {
        return new WebResult(resultEnum, customMsg);
    }

    public WebResult<T> update(ResultType resultType) {
        this.code = resultType.getCode();
        this.message = resultType.getDesc();
        return this;
    }

    public WebResult<T> update(ResultType resultType, String customMsg) {
        this.code = resultType.getCode();
        this.message = customMsg;
        return this;
    }

    public WebResult(Result<T> result) {
        if (result.isSuccess()) {
            this.code = CommonResultEnum.SUCCESS.getCode();
            this.message = CommonResultEnum.SUCCESS.getDesc();
        }
        else {
            ErrorDetail error = result.getError();
            this.code = error.getCode();
            this.message = error.getMsg();
        }
        this.data = result.getData();
    }
}
